package com.ht.module.sys.service.impl;

import com.ht.module.sys.entity.AutoDrwaView;
import com.ht.module.sys.entity.Result;
import com.ht.module.sys.entity.SysMenu;
import com.ht.module.sys.mapper.AutoDrawMapper;
import com.ht.module.sys.mapper.GenerateViewDataMapper;
import com.ht.module.sys.mapper.MenuMapper;
import com.ht.module.sys.service.AutoDrawService;
import com.ht.module.sys.entity.SysAttribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AutoDrawServiceImpl implements AutoDrawService {

    @Autowired
    private AutoDrawMapper autoDrawMapperl;

    @Autowired
    private GenerateViewDataMapper generateViewDataMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public Result addView(AutoDrwaView autoDrwaView) {

        int code = autoDrawMapperl.addView(autoDrwaView);

        List<Map<String,Object>> data = generateViewDataMapper.selectViewData(autoDrwaView.getViewSql());
        Date date = new Date();
        SysMenu menu = menuMapper.getIdByName(autoDrwaView.getMenu());
        for(Map<String,Object> data2 : data){
            for(String key : data2.keySet()){
                SysAttribute attribute = new SysAttribute();
                if(data2.get(key) instanceof Timestamp){
                    continue;
                }
                attribute.setMenuid(menu.getId());
                attribute.setTableorview(menu.getView());
                attribute.setLabel(key);
                attribute.setProp(key);
                attribute.setSqlid(menu.getView());
                attribute.setCreateuserid(autoDrwaView.getCreateuserid());
                attribute.setCreateusername(autoDrwaView.getCreateusername());
                attribute.setCreateDate(date);
                attribute.setSqlviewid(autoDrwaView.getViewSqlId());
                generateViewDataMapper.addAttribute(attribute);
            }
            break;
        }
        if(code > 0){
            return new Result(0,"新增视图成功",null);
        }
        return new Result(0,"新增视图失败",null);
    }

    @Override
    public Result getView(AutoDrwaView autoDrwaView) {
        AutoDrwaView data = autoDrawMapperl.getView(autoDrwaView);
        if(data != null){
            return new Result(0,"操作成功",data);
        }
        return new Result(0,"操作失败",null);
    }
}
